﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acme.TestSite.Objects;
using Acme.Northwind.EFDAL;
using Acme.Northwind.EFDAL.Entity;

namespace Acme.TestSite
{
	public partial class ProductItem : BasePersistablePage
	{
		#region Page Events

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			cmdSave.Click += new EventHandler(SaveData);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
		}

		#endregion

		#region Methods

		protected override nHydrate.EFCore.DataAccess.NHEntityObject CreateObject(NorthwindEntities context)
		{
			var newItem = new Acme.Northwind.EFDAL.Entity.Product();
			context.AddItem(newItem);
			return newItem;
		}

		protected override void SetupBindings(NorthwindEntities context)
		{
			var productId = this.Request["id"].ToInt32();
			var product = context.Product.FirstOrDefault(x => x.ProductId == productId);
			if (product == null)
				product = CreateObject(context) as Acme.Northwind.EFDAL.Entity.Product;

			Mapper.InitializeList(cboCategory, context.Category.ToList(), Acme.Northwind.EFDAL.Entity.Category.FieldNameConstants.Name, Acme.Northwind.EFDAL.Entity.Category.FieldNameConstants.CategoryId);
			Mapper.InitializeList(cboSupplier, context.Supplier.ToList(), Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.CompanyName, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.UserId);

			Mapper.Map(lblProductId, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.ProductId);
			Mapper.Map(txtInStock, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.UnitsInStock, lblInStock);
			Mapper.Map(txtName, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.Name, lblName);
			Mapper.Map(txtOnOrder, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.UnitsOnOrder, lblOnOrder);
			Mapper.Map(txtPrice, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.UnitPrice, lblPrice);
			Mapper.Map(txtQuantityPerUnit, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.QuantityPerUnit, lblQuantityPerUnit);
			Mapper.Map(cboSupplier, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.SupplierId, lblSupplier);
			Mapper.Map(cboCategory, product, Acme.Northwind.EFDAL.Entity.Product.FieldNameConstants.CategoryId, lblCategory);
		}

		#endregion

		#region Event Handlers

		private void cmdCancel_Click(object sender, EventArgs e)
		{
			this.Response.Redirect(SessionHelper.LastProductListSearch);
		}

		protected override void OnDataSavedSucess(EventArgs e)
		{
			base.OnDataSavedSucess(e);
			this.Response.Redirect(SessionHelper.LastProductListSearch);
		}

		#endregion

	}
}